package cc.grapevine.netcard.tools;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.DataOutputStream;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author jerryzhang
 * 
 */
public class BaseAuthenicationHttpClient {

	public static String app_token_param = ApiString.APP + "="
			+ ApiString.APP_VALUE;

	/**
	 * 
	 * @param urlString
	 * @param params
	 *            ���ݲ���
	 * @return ���ػ��
	 * @throws IOException
	 */
	static public String doPost(String urlString, HashMap<String, String> params)
			throws IOException {

		URL url = new URL(urlString);

		HttpURLConnection uc = (HttpURLConnection) url.openConnection();
		uc.setRequestProperty("User-Agent", "Mozilla/5.0");

		uc.setDoInput(true);
		uc.setDoOutput(true);
		uc.setRequestMethod("POST");

		if (params != null && !params.isEmpty()) {
			StringBuffer buf = new StringBuffer(app_token_param);
			for (String key : params.keySet()) {
				buf.append("&").append(key).append("=").append(params.get(key));
			}
			// buf.deleteCharAt(0);
			uc.getOutputStream().write(buf.toString().getBytes("UTF-8"));
			uc.getOutputStream().close();
		}

		InputStream content = (InputStream) uc.getInputStream();
		BufferedReader in = new BufferedReader(new InputStreamReader(content,
				"UTF-8"));
		String line = in.readLine();// will refactory
		// while ((line = in.readLine()) != null) {
		// System.out.println (line);
		// }
		in.close();
		return line.trim();

	}

	static public String doGet(String urlString, HashMap<String, String> params)
			throws IOException {

		StringBuffer buf = new StringBuffer(urlString + "?" + app_token_param);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				buf.append("&").append(key).append("=").append(params.get(key));
			}
		}

		URL url = new URL(buf.toString().trim());

		URLConnection uc = url.openConnection();

		uc.setRequestProperty("User-Agent", "Mozilla/5.0");

		InputStream content = (InputStream) uc.getInputStream();
		BufferedReader in = new BufferedReader(new InputStreamReader(content,
				"UTF-8"));
		String line = in.readLine();// will refactory

		in.close();
		return line.trim();

	}

}
